﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Toom.CellularAutomata.Model
{
	public class CAFieldChunk
	{
		// CTOR
		public CAFieldChunk( int myBaseX, int myBaseY )
		{
			this.mybaseX = myBaseX;
			this.mybaseY = myBaseY;

			this.neighbors = new int[8];
			this.neighborsCount = 0;

			this.state = CAFieldChunkState.Virgin;
		}

		// DATA
		public static readonly int CHUNK_SIZE = 64;		// was 8
		public static readonly int FILLER_CELL_VALUE = 0;

		private int[] data		= new int[CHUNK_SIZE * CHUNK_SIZE];
		private int[] dataNew	= new int[CHUNK_SIZE * CHUNK_SIZE];

		public int mybaseX, mybaseY;

		public int[] neighbors;			// chunk indexes
		public int neighborsCount;

		public CAFieldChunkState state;


		// converters coords to index, and vv
		public int convertXYtoIdx( int x, int y )
		{
			return y*CHUNK_SIZE + x;
		}


		// get and set: data and dataNew
		public int GetDataAbsolute( int x, int y )
		{
			x -= mybaseX;
			y -= mybaseY;

			if ( x<0 || x>CHUNK_SIZE || y<0 || y>CHUNK_SIZE )
				throw new Exception( "requested coords "+x+","+y+" are outside of my chunk" );

			int idx = convertXYtoIdx( x, y );
			return data[idx];
		}
		public void SetNewDataAbsolute( int x, int y, int newVal )
		{
			x -= mybaseX;
			y -= mybaseY;

			if ( x<0 || x>CHUNK_SIZE || y<0 || y>CHUNK_SIZE )
				throw new Exception( "requested coords "+x+","+y+" are outside of my chunk" );

			int idx = convertXYtoIdx( x, y );
			dataNew[idx] = newVal;

			// if we just set a non-background cell, mark us as Active
			if ( newVal > FILLER_CELL_VALUE )
				state = CAFieldChunkState.Active;
		}

		public void SetDataAbsolute( int x, int y, int newVal )
		{
			x -= mybaseX;
			y -= mybaseY;

			if ( x<0 || x>CHUNK_SIZE || y<0 || y>CHUNK_SIZE )
				throw new Exception( "requested coords "+x+","+y+" are outside of my chunk" );

			int idx = convertXYtoIdx( x, y );
			data[idx] = newVal;

			// if we just set a non-background cell, mark us as Active
			if ( newVal > FILLER_CELL_VALUE )
				state = CAFieldChunkState.Active;

		}

		// to switch from data to dataNew
		public void GotoNewTime()
		{
			int[] t;
			t = data;
			data = dataNew;
			dataNew = t;		//new int[CHUNK_SIZE * CHUNK_SIZE];
		
			// now we need to wipe t
			for ( int i=0; i<t.Length; i++)
				dataNew[i] = -1;
		}

	}



	public enum CAFieldChunkState
	{
		Virgin = 0,
		Warm = 1,
		Active = 2
	}


}



